package com.east.sng.aspect;


import com.east.sng.entity.param.SyslogParam;
import com.east.sng.entity.result.UserFind;
import com.east.sng.service.RoleService;
import com.east.sng.service.SyslogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * @author east
 * @date: 2021/1/4
 * @Description: system login log insert aspect
 **/
@Aspect
@Component
public class SyslogAspect {
    @Autowired
    private SyslogService syslogService;
    @Autowired
    private RoleService roleService;

    @Pointcut("execution(* * ..controller.*.login(..))")
    public void syslogPointcut(){}

    /**
     * 记录登录日志
     */
    @AfterReturning(value = "syslogPointcut()",returning = "value")
    public void logRecord(Object value) {
        //判断是否登录成功
        if ("redirect:/index".equals(value)) {
            //获取角色名称
            UserFind u = (UserFind) SecurityUtils.getSubject().getPrincipal();
            if (u != null) {
                String roleName = roleService.findRole(u.getRoleId()).getRoleName();
                //拼接用户名和角色名称得到日志名称
                String logName = "loginUser:"+u.getUserName()+"=>roleName:"+roleName;
                //通过RequestContextHolder获取用户ip地址
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                String addrIp = ((ServletRequestAttributes)requestAttributes).getRequest().getRemoteAddr();
                //添加日志
                syslogService.addSyslog(new SyslogParam(logName,addrIp,new Date()));
            }
        }
    }

}
